<?php
include_once '../config/DatabaseHandler.php';
include_once '../classes/Usuario.php';

function __autoload($class_name) {
    include $class_name . '.php';
}

function login() {

    if (isset($_POST['usuario'])) $username = $_POST['usuario'];
    if (isset($_POST['password'])) $password = $_POST['password'];

    $usuario = validarLogin($username, $password);
    if ($usuario) {
    	@session_start();
        // Time limit config
       // set_time_limit(30);
    	$_SESSION['current_user']= $usuario;
        $_SESSION['current_user']['time'] = time();
        echo json_encode($usuario);
    } else{ 
    	echo json_encode('fail');
    }
}

function validarLogin($nombre, $password) {

    
    $password_md5 = md5($password);
    $db = new DatabaseHandler();
    $db->connect();
    
    
    $where = ' nombre = "'. $nombre .'" and password="'.$password_md5. '"';
    $db->select(Usuario::getNombreTabla(),' * ',$where);
    return $db->getUniqueResult();

   
}

function secure($role) {

	$redirected_page = '';
	$current_page = explode ("/", $_SERVER["PHP_SELF"]);
	$current_page = $current_page[sizeof($current_page)-1];
	$current_page = explode (".", $current_page);
	$current_page = $current_page[0];
	
	
	if (user_has_valid_session ()) {
		 
		if(contains_rol($role, get_user_roles())){
			return;
		}else{
			$redirected_page = 'access-denied';
		}
				
	} else {
		if ($current_page == 'login') return;
		$redirected_page = 'login?previous_page='.$current_page;
	}
	header('Location: /' . $redirected_page);
}


function user_has_valid_session() {
    if (isset($_SESSION['current_user'])) {
		return true;
	}
    
	return false;
}

function contains_rol($role, $roles){
	foreach ($roles as $usrRole){
		if(strnatcasecmp($usrRole['descripcion'], $role) == 0)
			return true;
	} 
	
	return false;
}

function get_user_roles(){
	
	$db = new DatabaseHandler();
	$db->connect();
	$db->freeQuery("Select r.descripcion from rol r INNER JOIN usuario_rol where usuario_id = ". $_SESSION['current_user']['id']);
	return $db->getResult();
}

function check_valid_session() {
    if (user_has_valid_session() == true) return true;
    else terminate_session(); // Session expired or not valid
}

function terminate_session() {
	session_start();
	$_SESSION = array();
    session_destroy();
}

function logout(){
	terminate_session();
	echo json_encode('success');
}
?>

